/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.store.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.store.entity.StoreArea;
import com.thinkgem.jeesite.modules.store.entity.StoreTree;
import com.thinkgem.jeesite.modules.store.service.StoreAreaService;
import com.thinkgem.jeesite.modules.store.service.StoreTreeService;

/**
 * 门店区域划分表Controller
 * @author whh
 * @version 2017-09-06
 */
@Controller
@RequestMapping(value = "${adminPath}/store/storeTree")
public class StoreTreeController extends BaseController {
	
	
	@Autowired
	private StoreTreeService storeTreeService;
	@Autowired
	private StoreAreaService storeAreaService;
	
	@ModelAttribute
	public StoreTree get(@RequestParam(required=false) String id) {
		StoreTree entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = storeTreeService.get(id);
		}
		if (entity == null){
			entity = new StoreTree();
		}
		return entity;
	}
	
	/*
	 * 获取StoreArea通过StoreId
	 */
	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = "getStoreAreaByStoreId")
	public void getStoreAreaByStoreId(HttpServletRequest request,HttpServletResponse response){
		HashMap<String,String> parameter = getParameter(request);
		StoreArea storeArea = storeAreaService.getStoreAreaByStoreId(parameter.get("storeId"));
		backMessage(response,storeArea);
	}
	
	/*
	 * 添加修改信息框内容
	 */
	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = "updateRemarks")
	public void updateRemarks(HttpServletRequest request,HttpServletResponse response){
		HashMap<String,String> parameter = getParameter(request);
		HashMap<String,String> message = new HashMap<String,String>();
		StoreArea storeArea = storeAreaService.getStoreAreaByStoreId(parameter.get("storeId"));
		storeArea.setRemarks(parameter.get("remarks"));
		storeAreaService.save(storeArea);
		message.put("info","success");
		backMessage(response, message);
	}
	
	/*
	 * 删除门店经纬度
	 */
	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = "deleteStoreArea")
	public void deleteStoreArea(HttpServletRequest request,HttpServletResponse response){
		HashMap<String,String> parameter = getParameter(request);
		HashMap<String,String> message = new HashMap<String,String>();
		StoreArea storeArea = storeAreaService.getStoreAreaByStoreId(parameter.get("storeId"));
		storeAreaService.delete(storeArea);
		message.put("info","success");
		backMessage(response, message);
	}
	
	/*
	 * 给门店添加经纬度
	 */
	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = "addStoreArea")
	public void addStoreArea(HttpServletRequest request,HttpServletResponse response){
		HashMap<String,String> parameter = getParameter(request);
		HashMap<String,String> message = new HashMap<String,String>();
		StoreArea storeArea = new StoreArea();
		storeArea.setLongitude(parameter.get("lng"));
		storeArea.setDimension(parameter.get("lat"));
		storeArea.setStoreId(parameter.get("storeId"));
		StoreArea oldStoreArea = storeAreaService.getStoreAreaByStoreId(parameter.get("storeId"));
		StoreTree storeTree = storeTreeService.get(parameter.get("storeId"));
		storeArea.setRemarks(storeTree.getRemarks());
		if(null != oldStoreArea){
		storeArea.setId(oldStoreArea.getId());
		}
		storeAreaService.save(storeArea);
		message.put("info","success");
		backMessage(response,message);
		}
	
	/**
	 * 转换成json格式
	 */
	public static StringWriter Message2Json(Object obj){
		StringWriter str = new StringWriter();
		ObjectMapper objMapper = new ObjectMapper();
		try {
			objMapper.writeValue(str,obj);
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return str;
	}
	
	/*
	 * 打印返回信息
	 */
	public void backMessage(HttpServletResponse response,Object obj){
		StringWriter str = Message2Json(obj);
		PrintWriter writer = null;
		try {
		    writer = response.getWriter();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		writer.println(str);
	}
	
	
	/*
	 *跳转到门店查询页面 
	 */
	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = "storeIndex")
	public String storeIndex(Model model) {
		return "modules/store/storeIndex";
	}
	
	public static void main(String[] args) {
		List list = new ArrayList();
		StoreArea s = new StoreArea();
		StoreArea s1 = new StoreArea();
		StoreArea s2 = new StoreArea();
		s.setId("212");s.setDelFlag("dfa");s.setDimension("dfafd");
		s1.setId("111");s1.setDelFlag("222");s1.setDimension("111");
		s2.setId("222");s2.setDelFlag("111");s2.setDimension("222");
		list.add(s);
		list.add(s2);
		list.add(s1);
		System.out.println(Message2Json(list));
	}
	
	/*
	 *进入首页面 
	 */
	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = "none")
	public String none(StoreTree storeTree, HttpServletRequest request, HttpServletResponse response, Model model) {
		HashMap<String,String> parameter = getParameter(request);
		String storeId = parameter.get("storeTree.id");
		if(StringUtils.isNoneBlank(storeId) && !"".equals(storeId)){
			request.setAttribute("storeId",storeId);
			List<String> idList = storeTreeService.findChildsIdByStoreId(storeId);
			idList.add(storeId);
			List<StoreArea> storeAreaList = storeAreaService.findStoreAreaListByIdList(idList);
			StringWriter storeAreaJson = Message2Json(storeAreaList);
			request.setAttribute("storeAreaList",storeAreaJson);
		}
		return "modules/store/storeNone";
	}
	
	/*
	 *获取请求参数 
	 */
	public HashMap<String,String> getParameter(HttpServletRequest request){
		HashMap<String,String> parameter = new HashMap<String,String>();
		Enumeration<String> names = request.getParameterNames();
		while(names.hasMoreElements()){
			String key = names.nextElement();
			parameter.put(key,request.getParameter(key));
		}
		return parameter;
	}
	
	/*
	 *加载树 
	 */
	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = "tree")
	public String tree(Model model,HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("storeTreeList",storeTreeService.findByUser(true, null));
		return "modules/store/storeTree";
	}
	
	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = {"list", ""})
	public String list(StoreTree storeTree, HttpServletRequest request, HttpServletResponse response, Model model) {
		List<StoreTree> list = storeTreeService.findList(storeTree); 
		model.addAttribute("list", list);
		return "modules/store/storeTreeList";
	}

	@RequiresPermissions("store:storeTree:view")
	@RequestMapping(value = "form")
	public String form(StoreTree storeTree, Model model) {
		if (storeTree.getParent()!=null && StringUtils.isNotBlank(storeTree.getParent().getId())){
			storeTree.setParent(storeTreeService.get(storeTree.getParent().getId()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(storeTree.getId())){
				StoreTree storeTreeChild = new StoreTree();
				storeTreeChild.setParent(new StoreTree(storeTree.getParent().getId()));
				List<StoreTree> list = storeTreeService.findList(storeTree); 
				if (list.size() > 0){
					storeTree.setSort(list.get(list.size()-1).getSort());
					if (storeTree.getSort() != null){
						storeTree.setSort(storeTree.getSort() + 30);
					}
				}
			}
		}
		if (storeTree.getSort() == null){
			storeTree.setSort(30);
		}
		model.addAttribute("storeTree", storeTree);
		return "modules/store/storeTreeForm";
	}

	@RequiresPermissions("store:storeTree:edit")
	@RequestMapping(value = "save")
	public String save(StoreTree storeTree, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, storeTree)){
			return form(storeTree, model);
		}
		storeTreeService.save(storeTree);
		addMessage(redirectAttributes, "保存门店区域划分表成功");
		return "redirect:"+Global.getAdminPath()+"/store/storeTree/?repage";
	}
	
	@RequiresPermissions("store:storeTree:edit")
	@RequestMapping(value = "delete")
	public String delete(StoreTree storeTree, RedirectAttributes redirectAttributes) {
		storeTreeService.delete(storeTree);
		addMessage(redirectAttributes, "删除门店区域划分表成功");
		return "redirect:"+Global.getAdminPath()+"/store/storeTree/?repage";
	}

	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<StoreTree> list = storeTreeService.findList(new StoreTree());
		for (int i=0; i<list.size(); i++){
			StoreTree e = list.get(i);
			if (StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1)){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("name", e.getName());
				mapList.add(map);
			}
		}
		return mapList;
	}
	
}